﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using PetaPoco;
using Qy.Common;
using Qy.Models;
using Qy.Service;
using Qy.Web.Authorize;
using Qy.Web.Hubs;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Qy.Web.Api
{
    [Route("Api/[controller]/[action]")]
    [Verify]
    public class NoticeController : Base
    {
        private readonly LoginUtil _LoginUtil;
        private readonly NoticeKeyService _notice;
        private readonly ConfigService _configService;
        private readonly AttmentService _attment;
        private readonly UserService _user;
        private readonly MessageHub _messageHub;
        public NoticeController(LoginUtil LoginUtil,
            UserService adminUserService,
            AttmentService attmentService,
            ConfigService configService,
            NoticeKeyService noticeKeyService, MessageHub messageHub
            )
        {
            _LoginUtil = LoginUtil;
            _notice = noticeKeyService;
            _user = adminUserService;
            _configService = configService;
            _attment = attmentService;
            _messageHub = messageHub;
        }

        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_Index)]
        public async Task<IActionResult> IndexAsync([FromQuery] NoticeQuery query)
        {
            query.Uid = _LoginUtil.LoginUserId();
            Page<ViewNotice> list = await _notice.GetPageListAsync(query);
            return Json(new { status = 1, data = list.Items, count = list.TotalItems });
        }

        [HttpGet, ActionName("Read")]
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_Index)]
        public async Task<IActionResult> ReadAsync([FromQuery]int id)
        {
            if (id <1)
            {
                return Json(new { status = 0, msg="ID错误！" });
            }
            int uid = _LoginUtil.LoginUserId();
            ViewNotice notice = await _notice.ReadAsync(id, uid);
            List<ViewAttment> attments = null;
            if (!string.IsNullOrEmpty(notice.Att))
                attments = await _attment.GetListAsync(notice.Att);
            return Json(new { status = 1, data = notice, attments });
        }
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_AddOrEdit)]
        public async Task<IActionResult> AddOrEditAsync()
        {
            //返回没有自己的用户列表
            return Json(new { status = 1, userList = await _user.GetNameAsync(_LoginUtil.LoginUserId()) });
        }

        [HttpPost, ActionName("Create")]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_AddOrEdit)]
        [Log(Name = "发布消息")]
        public async Task<IActionResult> CreatePostAsync([FromBody] EditNotice editNotice)
        {
            if (ModelState.IsValid)
            {
                UserAction user = _LoginUtil.UserAction();
                await _notice.InsertAsync(editNotice, user.UserId);
                return Json(new { status = 1, msg = "发送消息 目标ID：" + editNotice.GetUid });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }

        /// <summary>
        /// 发送通知公告表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_AddOrEdit)]
        public async Task<IActionResult> SendNoticeAsync(int noticeId = 0)
        {
            if (noticeId <= 0)
            {
                return Json(new { status = 0, msg = "请求实体为空" });
            }
            ViewNotice response = await _notice.ReadOneAsync(noticeId);
            if (response != null)
            {
                await _messageHub.Clients.All.SendAsync(HubsConstant.ReceiveNotice, response.Title, response.Content);
            }
            return Json(new { status = 1, msg = "发送成功！" });
        }
        [HttpDelete]
        [ActionPermissionFilter(Permission = PermissionKeys.Notice_Delete)]
        [Log(Name = "删除消息")]
        public async Task<IActionResult> Delete(int id)
        {
            if (await _notice.DeleteByPriKeyAsync(id) > 0)
            {
                return Json(new { status = 1, msg = "删除消息 ID：" + id });
            }
            else
                return Json(new { status = 0, msg = "删除失败 ID：" + id });
        }

    }
}
